package cn.zjnu.study.service;

import cn.zjnu.study.bean.GlobalProperties;
import cn.zjnu.study.bean.User;
import cn.zjnu.study.bean.UserExample;
import cn.zjnu.study.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GlobalProperties globalProperties;

    public User getUserByName(String userName) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUserNameEqualTo(userName);
        List<User> users = userMapper.selectByExample(userExample);
        if (users.size() == 0) {
            return null;
        }
        return users.get(0);
    }

    public void addUser(User user) {
        userMapper.insertSelective(user);
        File file = new File(globalProperties.getBasePath() + "/" +
                getUserByName(user.getUserName()).getUserId());
        file.mkdirs();
    }

    public void updateUser(User user) {
        userMapper.updateByPrimaryKey(user);
    }

    public void uploadIcon(MultipartFile file, User user) throws IOException {
        String path = "/" + user.getUserId() + "/icon.png";
        String realPath = globalProperties.getBasePath() + path;
        user.setUserIcon(path);
        updateUser(user);
        InputStream is = file.getInputStream();
        File outFile = new File(realPath);
        outFile.getParentFile().mkdirs();
        Files.copy(is, outFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }

    public User getUserById(int userId) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<User> users = userMapper.selectByExample(example);
        if (users.size() == 0) {
            return null;
        }
        return users.get(0);
    }
}
